package com.wn.common.net.support

import androidx.lifecycle.LiveData
import com.wn.common.net.model.ApiResponse
import com.wn.common.net.model.UNKNOWN_ERROR_CODE
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Callback
import retrofit2.Response
import java.lang.reflect.Type
import java.util.concurrent.atomic.AtomicBoolean

/**
 * @Author: wn
 * @Date: 2023/1/10 17:06
 * @Description: 可用于将retrofit的call回调数据转化为 liveData 的adapter  -- liveData
 */

class LiveDataCallAdapter<R>(private val responseType: Type) :
  CallAdapter<R, LiveData<ApiResponse>> {
  override fun adapt(call: Call<R>): LiveData<ApiResponse> {
    return object : LiveData<ApiResponse>() {
      private var started = AtomicBoolean(false)
      override fun onActive() {
        super.onActive()
        if (started.compareAndSet(false, true)) {
          call.enqueue(object : Callback<R> {
            override fun onResponse(call: Call<R>, response: Response<R>) {
              postValue(ApiResponse.create(response))
            }

            override fun onFailure(call: Call<R>, t: Throwable) {
              postValue(ApiResponse.create(UNKNOWN_ERROR_CODE, t))
            }
          })
        }
      }
    }
  }

  override fun responseType() = responseType
}
